<template>
  <div id="panel">
    <el-card class="queryForm">
      <el-form
        ref="queryForm"
        :model="queryParams"
        :inline="true"
        :label-position="'right'"
      >
        <el-form-item label="行政区划：" prop="countycode">
          <el-select
            v-model="queryParams.countycode"
            placeholder="选择区域"
            clearable
            style="width: 150px"
          >
            <el-option
              v-for="item in regionList"
              :key="item.code"
              :label="item.name"
              :value="item.code"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否污水处理厂：" prop="issewagefarm">
          <el-select
            v-model="queryParams.issewagefarm"
            placeholder="全部"
            clearable
            style="width: 150px"
          >
            <el-option
              v-for="item in isWWTPOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="企业名称：" prop="pollutename">
          <el-input
            style="width: 150px"
            v-model="queryParams.pollutename"
            placeholder="请输入企业名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="排放口名称：" prop="outportname">
          <el-input
            style="width: 150px"
            v-model="queryParams.outportname"
            placeholder="请输入排放口名称"
          ></el-input>
        </el-form-item>
        <div class="searchBtnBox">
          <el-button
            type="primary"
            icon="el-icon-search"
            @click="handleQuery"
            style="padding: 10px"
            >查询</el-button
          >
          <el-button @click="resetQuery" style="padding: 10px">
            <i class="iconfont icon-saoba"></i>
            重置
          </el-button>
        </div>
      </el-form>
    </el-card>
    <el-card class="pageContent">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            >新增</el-button
          >
        </el-col>
      </el-row>
      <el-table
        :data="tableList.rows"
        stripe
        :height="tableHeight"
        v-loading="loading"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column type="index" label="序号"> </el-table-column>
        <el-table-column prop="outportname" label="排放口名称" />
        <el-table-column prop="watchtype" label="监测方式">
          <template slot-scope="scope">
            {{ getLabelByValue(scope.row.watchtype) }}
          </template>
        </el-table-column>
        <el-table-column prop="pollutename" label="企业名称" />
        <el-table-column prop="outportname" label="排口名称" />
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button type="text" @click="view(scope.row)">详情</el-button>
            <el-button type="text" @click="handleUpdate(scope.row)"
              >修改</el-button
            >
            <el-button type="text" @click="handleDelete(scope.row)"
              >删除</el-button
            >
            <el-button type="text" @click="monitor(scope.row)"
              >监测项</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        class="pagination-self"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :pager-count="5"
        :current-page="queryParams.pageNum"
        :page-size="queryParams.pageSize"
        layout="slot, total, sizes, prev, pager, next, jumper"
        :total="tableList.total"
      >
        <el-button
          class="refresh-button"
          icon="el-icon-refresh"
          title="刷新"
          @click="getList"
        />
      </el-pagination>
    </el-card>

    <!-- 添加/编辑/查看排口信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="950px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <!-- 污染物列表表格，新增时隐藏 -->
        <el-row style="padding-bottom: 20px" v-if="title !== '添加排口信息'">
          <el-col :span="24">
            <el-table
              :data="form.pollutantList"
              border
              style="width: 100%; margin-top: 10px"
            >
              <el-table-column
                type="index"
                label="序号"
                width="60"
                align="center"
              ></el-table-column>
              <el-table-column
                prop="pollutantname"
                label="因子名称"
                align="center"
              ></el-table-column>
              <el-table-column
                prop="warmtype"
                label="报警类型"
                align="center"
                :formatter="formatWarmType"
              ></el-table-column>
              <el-table-column
                prop="standardval"
                label="标准值"
                align="center"
              ></el-table-column>
              <el-table-column
                prop="prewarnupper"
                label="预警上限"
                align="center"
              ></el-table-column>
              <el-table-column
                prop="prewarnlower"
                label="预警下限"
                align="center"
              ></el-table-column>
              <el-table-column
                prop="warnupper"
                label="报警上限"
                align="center"
              ></el-table-column>
              <el-table-column
                prop="warnlower"
                label="报警下限"
                align="center"
              ></el-table-column>
              <el-table-column label="操作" align="center" width="100">
                <template slot-scope="scope">
                  <el-button
                    type="text"
                    @click="handlePollutantEdit(scope.row)"
                    :disabled="title === '查看排口信息'"
                  >
                    编辑
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-col>
        </el-row>
        <el-row>
          <!-- <el-col :span="12">
            <el-form-item label="行政区划" prop="countycode">
              <el-select
                v-model="form.countycode"
                placeholder="选择区域"
                style="width: 100%"
                clearable
                :disabled="title === '查看排口信息'"
              >
                <el-option
                  v-for="item in regionList"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col> -->
          <el-col :span="24">
            <el-form-item label="企业名称" prop="polluteid">
              <el-select
                v-model="form.polluteid"
                placeholder="请选择企业名称"
                style="width: 100%"
                clearable
                :disabled="title === '查看排口信息'"
              >
                <el-option
                  v-for="item in enterpriseOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="排放口名称" prop="outportname">
              <el-input
                v-model="form.outportname"
                placeholder="请输入排放口名称"
                maxlength="20"
                :disabled="title === '查看排口信息'"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="地址" prop="address">
              <el-input
                v-model="form.address"
                placeholder="请输入地址"
                :disabled="title === '查看排口信息'"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="经度" prop="longitude">
              <el-input
                v-model="form.longitude"
                placeholder="请输入经度"
                :disabled="title === '查看排口信息'"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="纬度" prop="latitude">
              <el-input
                v-model="form.latitude"
                placeholder="请输入纬度"
                :disabled="title === '查看排口信息'"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="排口类型" prop="outputtype">
              <el-select
                v-model="form.outputtype"
                placeholder="请选择排口类型"
                style="width: 100%"
                clearable
                :disabled="title === '查看排口信息'"
              >
                <el-option
                  v-for="item in outletTypeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="监测类型" prop="watchtype">
              <el-select
                v-model="form.watchtype"
                placeholder="请选择监测类型"
                style="width: 100%"
                clearable
                :disabled="title === '查看排口信息'"
              >
                <el-option
                  v-for="item in dict.type.monitor_methods"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="投产日期" prop="rundate">
              <el-date-picker
                v-model="form.rundate"
                type="date"
                placeholder="选择日期时间"
                style="width: 100%"
                value-format="yyyy-MM-dd"
                :disabled="title === '查看排口信息'"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="运行状态" prop="runstatus">
              <el-select
                v-model="form.runstatus"
                placeholder="请选择运行状态"
                style="width: 100%"
                clearable
                :disabled="title === '查看排口信息'"
              >
                <el-option
                  v-for="item in dict.type.run_status"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="监测频率" prop="watchfrequency">
              <el-select
                v-model="form.watchfrequency"
                placeholder="请选择监测频率"
                style="width: 100%"
                clearable
                :disabled="title === '查看排口信息'"
              >
                <el-option
                  v-for="item in dict.type.watch_frequency"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="上传" prop="file">
              <div class="langcont-left" style="position: relative">
                <el-upload
                  :action="baseUrl + '/common/upload'"
                  :headers="headers"
                  accept="image/jpeg,image/gif,image/png,image/jpg"
                  list-type="picture-card"
                  :limit="1"
                  :class="ImageUrlList.length > 0 || disabled ? 'hide' : ''"
                  :file-list="ImageUrlList"
                  :on-preview="handlePictureCardPreview"
                  :on-remove="handleRemove"
                  :on-success="handleSuccess"
                  :disabled="disabled || title === '查看排口信息'"
                  :before-upload="beforeUpload"
                >
                  <i class="el-icon-plus"></i>
                </el-upload>
                <div class="demo-image__preview" style="display: none">
                  <el-image
                    style="width: 100px; height: 100px"
                    class="myImg"
                    ref="myImg"
                    :src="ImagePreview[0]"
                    :preview-src-list="ImagePreview"
                  >
                  </el-image>
                </div>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          @click="submitForm"
          v-if="title !== '查看排口信息'"
        >
          确 定
        </el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 污染物编辑弹窗 -->
    <el-dialog
      title="编辑污染物监测项"
      :visible.sync="pollutantDialogVisible"
      width="600px"
      append-to-body
    >
      <el-form
        ref="pollutantForm"
        :model="currentPollutant"
        :rules="pollutantRules"
        label-width="120px"
      >
        <el-form-item label="因子名称" prop="pollutantname">
          <el-input v-model="currentPollutant.pollutantname" disabled />
        </el-form-item>
        <el-form-item label="报警类型" prop="warmtype">
          <el-select
            v-model="currentPollutant.warmtype"
            placeholder="请选择报警类型"
            style="width: 100%"
          >
            <el-option label="区间报警" :value="1"></el-option>
            <el-option label="上限报警" :value="2"></el-option>
            <el-option label="下限报警" :value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="标准值" prop="standardval">
          <el-input
            v-model="currentPollutant.standardval"
            placeholder="请输入标准值"
          />
        </el-form-item>
        <el-form-item label="预警上限" prop="prewarnupper">
          <el-input
            v-model="currentPollutant.prewarnupper"
            placeholder="请输入预警上限"
          />
        </el-form-item>
        <el-form-item label="预警下限" prop="prewarnlower">
          <el-input
            v-model="currentPollutant.prewarnlower"
            placeholder="请输入预警下限"
          />
        </el-form-item>
        <el-form-item label="报警上限" prop="warnupper">
          <el-input
            v-model="currentPollutant.warnupper"
            placeholder="请输入报警上限"
          />
        </el-form-item>
        <el-form-item label="报警下限" prop="warnlower">
          <el-input
            v-model="currentPollutant.warnlower"
            placeholder="请输入报警下限"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="pollutantDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="savePollutant">保存</el-button>
      </div>
    </el-dialog>

    <!-- 监测项弹窗 -->
    <el-dialog
      title="监测项设置"
      :visible.sync="monitorDialogVisible"
      width="700px"
      append-to-body
      :close-on-click-modal="false"
    >
      <div
        class="monitor-container"
        v-loading="monitorLoading"
        element-loading-text="加载监测项中..."
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(255, 255, 255, 0.8)"
      >
        <el-form>
          <el-form-item>
            <el-checkbox-group
              v-model="selectedMonitorItems"
              @change="handleMonitorItemChange"
            >
              <div class="monitor-item-grid">
                <el-checkbox
                  v-for="item in monitorItems"
                  :key="item.pollutantcode"
                  :label="item.pollutantcode"
                  class="monitor-item"
                >
                  {{ item.pollutantname }}
                </el-checkbox>
              </div>
            </el-checkbox-group>
          </el-form-item>
        </el-form>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="monitorDialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="saveMonitorItems">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import dayjs from "dayjs";
import { getToken } from "@/utils/auth";
import { getRegionList } from "@/api/dataResources/monitorData/region.js";
import {
  getQyTableList,
  addQyPk,
  updateQyPk,
  delQyPk,
  getQyPkDetail,
  getQyPkJcx,
  getQyList,
  addQyPkJcx,
  updateQyPkJcx,
} from "@/api/zhManagement.js";

export default {
  name: "OutletManagement",
  dicts: ["monitor_methods", "run_status", "watch_frequency"],
  data() {
    return {
      tableHeight: window.innerHeight - 480,
      regionList: [],
      baseUrl: this.$config,
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      // 图片上传相关
      ImageUrlList: [],
      ImagePreview: [""],
      photoFile: null,
      disabled: false,
      // 下拉选项相关
      enterpriseOptions: [],
      attentionLevelOptions: [
        { label: "全部", value: "全部" },
        { label: "重点关注", value: "重点关注" },
        { label: "一般关注", value: "一般关注" },
      ],
      isWWTPOptions: [
        { label: "全部", value: "全部" },
        { label: "是", value: "是" },
        { label: "否", value: "否" },
      ],
      outletTypeOptions: [
        { label: "进水口", value: "2" },
        { label: "出水口", value: "1" },
      ],
      monitorTypeOptions: [
        { label: "水质监测", value: "水质监测" },
        { label: "水量监测", value: "水量监测" },
      ],
      operationStatusOptions: [
        { label: "运行中", value: "运行中" },
        { label: "停运", value: "停运" },
        { label: "维护中", value: "维护中" },
      ],
      monitorFrequencyOptions: [
        { label: "每小时", value: "每小时" },
        { label: "每天", value: "每天" },
        { label: "每周", value: "每周" },
        { label: "每月", value: "每月" },
      ],
      // 表格相关
      fileList: [],
      loading: false,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        countycode: "",
        attentionLevel: "全部",
        issewagefarm: "全部",
        pollutename: "",
        outportname: "",
      },
      tableList: {
        total: 0,
        rows: [],
      },
      // 选中数组
      ids: [],
      // 弹窗相关
      open: false,
      title: "添加排口信息",
      form: {
        countycode: "",
        polluteid: "",
        outportname: "",
        outportcode: "",
        address: "",
        longitude: "",
        latitude: "",
        contact: "",
        phone: "",
        outputtype: "",
        watchtype: "",
        rundate: "",
        runstatus: "",
        watchfrequency: "",
        pollutantList: [], // 污染物列表
      },
      // 需要提交的字段列表
      submitFields: [
        "countycode",
        "polluteid",
        "outportname",
        "address",
        "longitude",
        "latitude",
        "contact",
        "phone",
        "outputtype",
        "watchtype",
        "rundate",
        "runstatus",
        "watchfrequency",
        "outportcode",
      ],
      rules: {
        polluteid: [
          { required: true, message: "企业名称不能为空", trigger: "blur" },
        ],
        outportname: [
          { required: true, message: "排放口名称不能为空", trigger: "blur" },
        ],
        longitude: [
          { required: true, message: "经度不能为空", trigger: "blur" },
        ],
        latitude: [
          { required: true, message: "纬度不能为空", trigger: "blur" },
        ],
        outputtype: [
          { required: true, message: "排口类型不能为空", trigger: "blur" },
        ],
      },
      // 污染物编辑弹窗相关
      pollutantDialogVisible: false,
      currentPollutant: {},
      pollutantRules: {
        warmtype: [
          { required: true, message: "请选择报警类型", trigger: "change" },
        ],
        standardval: [
          { required: true, message: "请输入标准值", trigger: "blur" },
        ],
      },
      // 监测项弹窗相关
      monitorDialogVisible: false,
      currentOutlet: null,
      monitorItems: [],
      selectedMonitorItems: [],
      monitorLoading: false,
    };
  },
  created() {
    this.getList();
    this.getRegionList();
    this.getEnterpriseList();
    // console.log(">>>", this.dict.type.monitor_methods);
  },
  mounted() {
    window.addEventListener("resize", this.handleResize);
    this.handleResize();
  },
  beforeDestroy() {
    window.removeEventListener("resize", this.handleResize);
  },
  methods: {
    // 根据 value 获取对应的 label，无匹配则返回 '-'
    getLabelByValue(targetValue) {
      // 从 options 中查找 value 匹配的项
      const matched = this.dict.type.monitor_methods.find(
        (item) => item.value === targetValue
      );
      // 有匹配项则返回 label，否则返回 '-'
      return matched ? matched.label : "-";
    },
    // 处理窗口大小变化
    handleResize() {
      this.tableHeight = window.innerHeight - 480;
    },

    async getRegionList() {
      let res = await getRegionList();
      if (res.code == 200) {
        this.regionList = res.rows;
      }
    },
    // 获取企业列表
    getEnterpriseList() {
      getQyList().then((res) => {
        if (res.code === 200) {
          this.enterpriseOptions = res.data.map((item) => ({
            label: item.pollutename,
            value: item.polluteid,
          }));
        }
      });
    },
    // 图片预览
    handlePictureCardPreview(file) {
      this.ImagePreview[0] = file.url;
      this.$refs.myImg.showViewer = true;
    },
    // 图片上传成功
    handleSuccess(response, file, fileList) {
      if (response.code == 200) {
        this.ImageUrlList = [];
        fileList.forEach((item) => {
          if (item.response) {
            this.ImageUrlList.push(item.response);
          } else {
            this.ImageUrlList.push(item);
          }
        });
        this.photoFile = response.fileName;
      }
    },
    // 图片移除
    handleRemove(file, fileList) {
      this.ImageUrlList = [];
      this.photoFile = null;
      fileList.forEach((item) => {
        if (item.response) {
          this.ImageUrlList.push(item.response);
        } else {
          this.ImageUrlList.push(item);
        }
      });
    },
    // 上传前校验
    beforeUpload(file) {
      const isJPG = file.type === "image/jpeg" || file.type === "image/png";
      const isLt500k = file.size / 1024 < 500;

      if (!isJPG) {
        this.$message.error("上传图片只能是 JPG/PNG 格式!");
      }
      if (!isLt500k) {
        this.$message.error("上传图片大小不能超过 500KB!");
      }
      return isJPG && isLt500k;
    },
    // 表格checkbox选择数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
    },
    // 过滤接口数据，仅保留form中已定义的字段
    filterFormFields(rawData) {
      const formKeys = Object.keys(this.form);
      const filteredData = formKeys.reduce((result, key) => {
        if (rawData.hasOwnProperty(key)) {
          result[key] = rawData[key];
        }
        return result;
      }, {});
      return filteredData;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.form = {
        countycode: "",
        polluteid: "",
        outportname: "",
        outportcode: "",
        address: "",
        longitude: "",
        latitude: "",
        contact: "",
        phone: "",
        outputtype: "",
        watchtype: "",
        rundate: "",
        runstatus: "",
        watchfrequency: "",
        pollutantList: [], // 初始化污染物列表
      };
      this.fileList = [];
      this.photoFile = null;
      this.ImageUrlList = [];
      this.open = true;
      this.title = "添加排口信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      getQyPkDetail(row.outportcode).then((res) => {
        if (res.code === 200) {
          const filteredData = this.filterFormFields(res.data);
          if (filteredData.rundate) {
            filteredData.rundate = dayjs(filteredData.rundate).format(
              "YYYY-MM-DD"
            );
          }
          // 赋值污染物列表
          this.form = {
            ...filteredData,
            pollutantList: res.data.pollutantList || [],
          };
          console.log(">>>formdatas", this.form);
        }
      });
      this.open = true;
      this.title = "修改排口信息";
    },
    /** 查看按钮操作 */
    view(row) {
      getQyPkDetail(row.outportcode).then((res) => {
        if (res.code === 200) {
          const filteredData = this.filterFormFields(res.data);
          if (filteredData.rundate) {
            filteredData.rundate = new Date(filteredData.rundate);
          }
          // 赋值污染物列表
          this.form = {
            ...filteredData,
            pollutantList: res.data.pollutantList || [],
          };
        }
      });
      this.open = true;
      this.title = "查看排口信息";
    },
    /** 编辑污染物项 */
    handlePollutantEdit(row) {
      // 深拷贝当前行数据，避免直接修改表格数据
      this.currentPollutant = JSON.parse(JSON.stringify(row));
      this.pollutantDialogVisible = true;
    },
    /** 保存污染物编辑 */
    savePollutant() {
      this.$refs.pollutantForm.validate((valid) => {
        if (valid) {
          console.log(">>>currentPollutant", this.currentPollutant);
          let query = JSON.parse(JSON.stringify(this.currentPollutant));
          delete query.createBy;
          delete query.createTime;
          updateQyPkJcx(query).then((res) => {
            if (res.code === 200) {
              // 找到对应的污染物并更新
              const index = this.form.pollutantList.findIndex(
                (item) =>
                  item.pollutantcode === this.currentPollutant.pollutantcode
              );
              if (index !== -1) {
                this.form.pollutantList.splice(index, 1, this.currentPollutant);
                this.$message.success("保存成功");
                this.pollutantDialogVisible = false;
              }
              // this.$message.success("保存成功");
              // this.pollutantDialogVisible = false;
            } else {
              this.$message.error(res.msg || "保存失败");
            }
          });
        }
      });
    },
    /** 格式化报警类型 */
    formatWarmType(row) {
      const warmTypeMap = {
        1: "区间报警",
        2: "上限报警",
        3: "下限报警",
      };
      return warmTypeMap[row.warmtype] || "-";
    },
    /** 监测项按钮操作 */
    monitor(row) {
      this.currentOutlet = row;
      this.monitorDialogVisible = true;
      this.monitorLoading = true;

      getQyPkJcx(row.outportcode)
        .then((res) => {
          this.monitorLoading = false;
          if (res.code === 200 && Array.isArray(res.data)) {
            this.monitorItems = res.data;
            this.selectedMonitorItems = res.data
              .filter((item) => item.status === "1")
              .map((item) => item.pollutantcode);
          } else {
            this.$message.error(res.msg || "获取监测项失败");
            this.monitorItems = [];
            this.selectedMonitorItems = [];
          }
        })
        .catch(() => {
          this.monitorLoading = false;
          this.$message.error("获取监测项异常");
          this.monitorItems = [];
          this.selectedMonitorItems = [];
        });
    },
    /** 监测项选择变化时 */
    handleMonitorItemChange(checkedCodes) {
      console.log("选中的监测项编码:", checkedCodes);
    },
    /** 保存监测项 */
    saveMonitorItems() {
      if (!this.currentOutlet || !this.currentOutlet.outportcode) {
        this.$message.error("缺少排放口信息");
        return;
      }

      const params = {
        outportcode: this.currentOutlet.outportcode,
        pollutantcode: this.selectedMonitorItems.join(","),
      };

      addQyPkJcx(params)
        .then((res) => {
          if (res.code === 200) {
            this.$message.success("监测项保存成功");
            this.monitorDialogVisible = false;
          } else {
            this.$message.error(res.msg || "保存失败");
          }
        })
        .catch(() => {
          this.$message.error("保存失败，请重试");
        });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      let id;
      if (row) {
        id = row.outportcode;
      } else {
        if (this.ids.length === 0) {
          this.$message.warning("请选择需要删除的排放口");
          return;
        }
        id = this.ids.join(",");
      }

      this.$modal
        .confirm("是否确认删除选中的排放口？")
        .then(() => {
          return delQyPk(id);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    // 分页
    handleSizeChange(val) {
      this.queryParams.pageSize = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.queryParams.pageNum = val;
      this.getList();
    },
    // 搜索
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    // 重置
    resetQuery() {
      this.$refs.queryForm.resetFields();
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        countycode: "",
        attentionLevel: "全部",
        issewagefarm: "全部",
        pollutename: "",
        outportname: "",
      };
      this.getList();
    },
    // 弹窗取消
    cancel() {
      this.open = false;
      this.pollutantDialogVisible = false;
      this.$refs.form && this.$refs.form.resetFields();
      this.$refs.pollutantForm && this.$refs.pollutantForm.resetFields();
      this.photoFile = null;
      this.ImageUrlList = [];
    },
    /** 提交表单 - 只提交指定字段和图片 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          const formData = new FormData();

          // 只添加需要提交的字段
          this.submitFields.forEach((key) => {
            formData.append(key, this.form[key] || "");
          });

          // 添加图片
          if (this.photoFile) {
            formData.append("photofile", this.photoFile.raw);
          } else {
            formData.append("photofile", "");
          }
          debugger;

          if (this.form.outportcode) {
            // 修改操作
            updateQyPk(formData).then((res) => {
              if (res.code === 200) {
                this.open = false;
                this.$modal.msgSuccess("修改成功");
                this.getList();
              }
            });
          } else {
            // 新增操作
            addQyPk(formData).then((res) => {
              if (res.code === 200) {
                this.open = false;
                this.$modal.msgSuccess("新增成功");
                this.getList();
              }
            });
          }
        }
      });
    },

    // 获取表格数据
    getList() {
      this.ids = [];
      this.loading = true;
      getQyTableList(this.queryParams)
        .then((res) => {
          if (res.code === 200) {
            this.tableList.total = res.total;
            this.tableList.rows = res.rows;
          }
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
        });
    },
  },
};
</script>
<style lang="scss" scoped>
p {
  margin: 0;
}

img {
  vertical-align: middle;
}

#panel {
  padding-bottom: 40px;
  min-height: calc(100% - 20px);
  margin: 0;

  // 分页样式
  .pagination-self {
    margin: 20px 0;
    display: flex;
    justify-content: flex-end;
    position: relative;

    .el-pagination__total {
      position: absolute;
      left: 5px;
      color: #409eff;
      font-weight: 600;
      font-size: 15px;
    }
  }

  // 刷新按钮
  .refresh-button {
    .el-icon-refresh {
      font-size: 18px;
      line-height: 28px;
    }
  }

  .el-card {
    margin: 10px;
  }

  .queryForm .el-card__body {
    padding: 0 20px !important;
  }

  .queryForm {
    .el-form-item {
      margin: 20px 0 20px 20px;
    }

    .el-form-item:first-child {
      margin-left: 0 !important;
    }

    .el-form-item__label {
      padding-right: 5px;
      color: #555;
    }

    .times {
      .el-form-item__content {
        width: 250px;
      }
    }

    .el-form-item__content {
      min-width: 200px;
    }

    .searchBtnBox {
      display: inline-block;
      margin: 20px 0 20px 20px;
    }
  }

  .pageContent {
    .tabs-list {
      padding-top: 10px;
    }

    .el-tabs__header {
      background: #fff;
    }

    .el-tabs__item {
      border: 1px solid #eee;
      margin: 0;
      border-left: 0;
      background: #fafbfc;
      color: #000;
    }

    .el-tabs__item:first-child {
      margin-left: 20px;
      border-left: 1px solid #eee;
    }

    .is-active {
      border-bottom: 0 !important;
      background: #fff;
      color: #307eff;
    }
  }

  .anjian label {
    padding: 0 !important;
    width: 100px !important;
  }

  .queryForm .el-checkbox {
    margin-right: 10px !important;
    width: auto !important;
  }

  .iszgfc .el-form-item__content {
    width: 120px;
  }
}

.titleBox {
  height: 50px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #dfe4ed;
  margin: 0 20px 20px 20px;
  position: relative;

  &::before {
    display: block;
    content: "";
    width: 3px;
    height: 16px;
    background: #307eff;
  }

  .title {
    font-size: 16px;
    color: #000;
    position: absolute;
    left: 10px;
    font-weight: 500;
  }

  .more {
    font-size: 16px;
    color: #999;
    cursor: pointer;
  }
}

// 监测项弹窗样式
.monitor-item-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  margin-top: 10px;
  max-height: 300px;
  overflow-y: auto;
  padding-right: 10px;
}

.monitor-item {
  margin-right: 0 !important;
  white-space: nowrap;
  padding: 2px 0;
}

.monitor-container {
  min-height: 300px;
}

// 隐藏上传按钮的样式
.hide .el-upload--picture-card {
  display: none;
}

// 污染物表格样式
::v-deep .el-table {
  margin-top: 10px;
}

::v-deep .el-table th {
  background-color: #f5f7fa;
  font-weight: 500;
}
</style>
